package cn.krund.lyc.hotlerobot.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.SystemClock;


import java.util.ArrayList;
import java.util.List;

import cn.krund.lyc.hotlerobot.Ros.common.entity.enums.RobotErrorInfo;
import cn.krund.lyc.hotlerobot.Ros.common.entity.enums.RobotFeedbackInfoType;
import cn.krund.lyc.hotlerobot.Ros.common.utils.Constant;
import cn.krund.lyc.hotlerobot.Ros.service.ICommunicationListener;
import cn.krund.lyc.hotlerobot.Ros.service.SocketServer;
import cn.krund.lyc.hotlerobot.Ros.service.UpdateCommunicationInfoTask;
import cn.krund.lyc.hotlerobot.Ros.service.bytetojsoninfohandler.ByteToJsonInfoHandlerContext;
import cn.krund.lyc.hotlerobot.Ros.service.bytetojsoninfohandler.IByteToJsonInfoHandler;
import cn.krund.lyc.hotlerobot.Ros.service.communication.IRosCommunicationListener;
import cn.krund.lyc.hotlerobot.Ros.service.communicationinfo.RosProtocolInfo;
import cn.krund.lyc.hotlerobot.utils.KrundLog;
import cn.krund.lyc.hotlerobot.utils.ToastUtils;

/**
 * @包名: cn.krund.lyc.hotlerobot.service
 * @作者: 刘育成
 * @时间: 2018/3/27  10:01
 * @org: 克路德人工智能
 * @描述: TODO
 * @fileName: RemoteControlService
 */

public class RemoteControlService extends Service implements ICommunicationListener {
    private Binder serviceBinder;
    private UpdateCommunicationInfoTask updataCommunicationInfoTask;                        // 更新通讯信息任务
    private List<ICommunicationListener> mList;                                                //通讯监听接口组
    private SocketServer mSocketServer;                                                    // 与Ros的通讯类

    @Override
    public IBinder onBind(Intent intent) {
        return this.serviceBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        this.mList = new ArrayList<>();
        this.initRosCommunication(Constant.SERVER_IP, Constant.SERVER_PORT);
        this.serviceBinder = new RemoteControlServiceBinder(RemoteControlService.this);


        //启动定时更新通讯信息任务
        this.updataCommunicationInfoTask = new UpdateCommunicationInfoTask(this);
        this.updataCommunicationInfoTask.startUpdata();
    }

    /**
     * 通讯链接
     *
     * @param serverIp   IP
     * @param serverPort 端口号
     */
    private void initRosCommunication(String serverIp, int serverPort) {
        this.mSocketServer = new SocketServer(serverPort);
        this.mSocketServer.setRosCommunicationListener(new IRosCommunicationListener() {
            @Override
            public void onConnectComplete(String ip, int port) {
                /**
                 * 网络连接完成
                 */
                SystemClock.sleep(2000);
                RemoteControlService.this.onConnectComplete();
                KrundLog.i("lyc>>>>>", "ip" + ip + "链接" + System.currentTimeMillis());
            }

            @Override
            public void onDisconnect(String ip, int port) {
                /**
                 * 网络连接断开
                 */
                RemoteControlService.this.onDisconnect();
                KrundLog.i("lyc>>>>>", "ip" + ip + "断开");
            }

            @Override
            public void recv(RosProtocolInfo rosProtocolInfo) {
                /**
                 * 接收到Ros的消息
                 *
                 * @param rosProtocolInfo
                 */
                IByteToJsonInfoHandler byteToJsonInfoHandler = new ByteToJsonInfoHandlerContext(rosProtocolInfo);
                byteToJsonInfoHandler.handler(RemoteControlService.this, rosProtocolInfo);
            }

            @Override
            public void exceptionHandler(Thread t, Throwable e) {

            }
        });
        this.mSocketServer.startRosCommunication();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mList.clear();
        this.updataCommunicationInfoTask.stopUpdata();
        this.mSocketServer.stopRosCommunication();
    }

    /**
     * 添加通讯监听
     *
     * @param listener
     */
    public void AddCommunicationListener(ICommunicationListener listener) {
        this.mList.add(listener);
    }

    /**
     * 移除通讯监听
     *
     * @param listener
     */
    public void removeCommunicationListener(ICommunicationListener listener) {
        this.mList.remove(listener);
    }

    /**
     * 给Ros发送命令
     *
     * @param rosProtocolInfo
     * @return
     */

    private boolean sendMsgToRos(RosProtocolInfo rosProtocolInfo) {
        return mSocketServer.sendMessage(rosProtocolInfo);
    }

    /**
     * 给Ros发送命令
     *
     * @param bytes 命令信息
     * @return
     */
    private boolean sendBytes(byte[] bytes) {
        return mSocketServer.sendBytes(bytes);
    }

    private boolean sendBytes(byte[] bytes, int off, int len) {
        return mSocketServer.sendBytes(bytes, off, len);
    }

    /******************ICommunicationListener***************************/

    @Override
    public void onConnectComplete() {
        for (int i = 0; i < mList.size(); i++) {
            ICommunicationListener listener = mList.get(i);
            if (listener != null) {
                listener.onConnectComplete();
            }
        }
    }

    @Override
    public void onDisconnect() {
        for (int i = 0; i < mList.size(); i++) {
            ICommunicationListener listener = mList.get(i);
            if (listener != null) {
                listener.onDisconnect();
            }
        }
    }

    @Override
    public void onFeedback(RobotFeedbackInfoType feedbackType, boolean isSucceed) {
        for (int i = 0; i < mList.size(); i++) {
            ICommunicationListener listener = mList.get(i);
            if (listener != null) {
                listener.onFeedback(feedbackType, isSucceed);
            }
        }
    }

    @Override
    public void onFeedback(RobotFeedbackInfoType feedbackType, Object feedbackInfo) {
        for (int i = 0; i < mList.size(); i++) {
            ICommunicationListener listener = mList.get(i);
            if (listener != null) {
                listener.onFeedback(feedbackType, feedbackInfo);
            }
        }
    }

    @Override
    public void onFeedback(RobotFeedbackInfoType feedbackType, Object feedbackInfo, boolean isSucceed) {
        for (int i = 0; i < mList.size(); i++) {
            ICommunicationListener listener = mList.get(i);
            if (listener != null) {
                listener.onFeedback(feedbackType, feedbackInfo, isSucceed);
            }
        }
    }

    @Override
    public void onRobotRealTimePos(float pointX, float pointY, float courseAngle) {
        for (int i = 0; i < mList.size(); i++) {
            ICommunicationListener listener = mList.get(i);
            if (listener != null) {
                listener.onRobotRealTimePos(pointX, pointY, courseAngle);
            }
        }
    }

    @Override
    public void onOSPFInfo(byte[] data) {
        for (int i = 0; i < mList.size(); i++) {
            ICommunicationListener listener = mList.get(i);
            if (listener != null) {
                listener.onOSPFInfo(data);
            }
        }
    }

    @Override
    public void onErrorInfo(RobotErrorInfo robotErrorInfo) {
        for (int i = 0; i < mList.size(); i++) {
            ICommunicationListener listener = mList.get(i);
            if (listener != null) {
                listener.onErrorInfo(robotErrorInfo);
            }
        }
    }
}
